<?php
	//测试同步异步任务效果，执行数据库写入操作
	function pushData()
	{
		$dbhost = '127.0.0.1';  // mysql服务器主机地址
	    $dbuser = 'root';            // mysql用户名
	    $dbpass = 'hwj199601';          // mysql password
	    $conn = mysqli_connect($dbhost, $dbuser, $dbpass);
	    mysqli_query($conn, "set names utf8");
	    mysqli_select_db( $conn, 'swoole' );
	    mysqli_query($conn, "SET AUTOCOMMIT=0"); // 设置为不自动提交，因为MYSQL默认立即执行
	    mysqli_begin_transaction($conn);    // 开始事务定义

	    for ($i = 0; $i < 1000; $i++) {
			$str = 'jslfjlkskfsdjlsdjlfjsdlfjdslfjsdljfldsjfldsfjksldjflsdkflskfjldsfjldskfldskfldskjfsdkjfldskfdslfjlsdfjslkfjlsdjflskjflsdfjslfjlsslfjls';
			$sql = "insert into test values (null, '".$str."', '".$str."', '".$str."')";
			$res = mysqli_query($conn, $sql);
			if (!$res) {
				mysqli_query($conn, "ROLLBACK");     // 判断当执行失败时回滚
			}
		}
		mysqli_commit($conn);            //执行事务
	    mysqli_close($conn);	
	}
	
	$host = '0.0.0.0'; //string
	$port = 9501; //int

	$serv = new swoole_server($host, $port);

	/**
	 * $serv 服务器信息
	 * $fd 客户端信息
	 */
	$serv->on('connect', function($serv, $fd){
		#echo "服务器信息：\n";
		#var_dump($serv);
		#echo "客户端信息：\n";
		#var_dump($fd);
		echo "建立连接成功!\n";
	});

	/**
	 * $from_id 客户端id
	 * $data 接受的数据
	 */
	$serv->on('receive', function($serv, $fd, $from_id, $data){
		echo "接受的数据,执行函数\n";
		pushData();
		#var_dump($from_id);
		#var_dump($data);
		$serv->send($fd, "Service: ".$data);	
	});

	$serv->on('close', function($serv, $fd){
		echo "连接关闭\n";
	});

	$serv->start(); //启动tcp服务器
